package com.chenfan.mcn.extension.excel;

import cn.afterturn.easypoi.cache.ImageCache;
import cn.afterturn.easypoi.entity.BaseTypeConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.afterturn.easypoi.util.PoiExcelGraphDataUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 定制Excel导出服务
 * @author wulg
 * @date 2021-10-26
 **/
public final class CustomExcelExportService extends ExcelExportService {

    private final String NULL_STRING = "null";

    @Override
    public void createSheetForMap(Workbook workbook, ExportParams entity,
                                  List<ExcelExportEntity> entityList, Collection<?> dataSet) {
        if(CollectionUtils.isNotEmpty(entityList)) {
            entityList.forEach(item -> {
                //标题宽度自适应
                if(StringUtils.isNotBlank(item.getName())) {
                    double defaultWidth = 11;
                    double expectedWidth = StringUtils.length(item.getName()) * 2 + 1;
                    item.setWidth(expectedWidth > defaultWidth ?  expectedWidth : defaultWidth);
                }
            });
        }
        super.createSheetForMap(workbook, entity, entityList, dataSet);
    }

    @Override
    public Object getCellValue(ExcelExportEntity entity, Object obj) throws Exception {
        if(Objects.nonNull(entity.getMethod())) {
            Class<?> returnType = entity.getMethod().getReturnType();
            if(Date.class.isAssignableFrom(returnType) || LocalDate.class.isAssignableFrom(returnType) || LocalDateTime.class.isAssignableFrom(returnType) ) {
                //默认日期格式
                if(StringUtils.isBlank(entity.getFormat())) {
                    entity.setFormat("yyyy/MM/dd");
                }
            } else if(Number.class.isAssignableFrom(returnType)) {
                entity.setType(BaseTypeConstants.DOUBLE_TYPE);
            }
        }
        Object value = super.getCellValue(entity, obj);
        //NULL转空
        if(value == null || StringUtils.isBlank(value.toString())) {
            return "";
        }
        //规避getCellValue->replace时，会将null转成"null"问题
        if(ArrayUtils.isNotEmpty(entity.getReplace()) && NULL_STRING.equals(StringUtils.trim(value.toString()))) {
            return "";
        }
        //默认CellType  导出excel单元格-数值-百分比不生效，待探究
        if(ArrayUtils.isNotEmpty(entity.getReplace())
                || StringUtils.isNotEmpty(entity.getFormat())
                || StringUtils.isNotEmpty(entity.getNumFormat())
                || StringUtils.isNotEmpty(entity.getSuffix())) {
            entity.setType(BaseTypeConstants.STRING_TYPE);
        }

        if(!BaseTypeConstants.STRING_TYPE.equals(entity.getType()) && !BaseTypeConstants.DOUBLE_TYPE.equals(entity.getType())) {
            //规避bug：BaseExportService=> createListCells
            if(!BaseTypeConstants.IMAGE_TYPE.equals(entity.getType())) {
                entity.setType(BaseTypeConstants.STRING_TYPE);
            }
        }
        return value;
    }

    /**
     * 图片类型的Cell
     */
    @Override
    public void createImageCell(Cell cell, double height, String imagePath, byte[] data) throws Exception {
        if (height > cell.getRow().getHeight()) {
            cell.getRow().setHeight((short) height);
        }
        ClientAnchor anchor;
        if (this.type.equals(ExcelType.HSSF)) {
            anchor = new HSSFClientAnchor(0, 0, 0, 0, (short)cell.getColumnIndex(), cell.getRow().getRowNum(), (short)(cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
        } else {
            anchor = new XSSFClientAnchor(0, 0, 0, 0, (short)cell.getColumnIndex(), cell.getRow().getRowNum(), (short)(cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
        }
        if (StringUtils.isNotEmpty(imagePath)) {
            data = ImageCache.getImage(imagePath);
        }
        if (data != null) {
            PoiExcelGraphDataUtil.getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
                    cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
        }
    }
}
